import React, { Component } from 'react'
// 声明状态，绑定状态，更新状态
const handleTime = (time) => {
    const secs = new Date().getTime() - new Date(time).getTime()
    const year = 1000*60*60*24*365
    if(secs/year>=1){
        return Math.floor(secs / year) +'年前'
    }
    return secs
}

class Topics extends Component {
    state={
        list: []
    }
    componentDidMount(){
        fetch('https://www.fastmock.site/mock/9e4bbf9e35ad15942010865690c87ac6/api/topics')
            .then(res=>res.json())
            .then(res=>{
                console.log(res);
                this.setState({list: res.data})
            })
    }
    render() {
        return (
            <div style={{flex:2}}>
                {
                    this.state.list.map((item,index)=>{
                        return (
                            <li 
                                key={item.id} 
                                style={{ backgroundColor: index%2==0?'#ccc':'#eee' }}
                            >
                                <img style={ {width: '60px'} } src={item.author.avatar_url} alt="" />
                                <span>{item.reply_count}</span>
                                /
                                <span>{item.visit_count}</span>
                                <span style={{ background: item.tab=='ask'?'red':'green' }}>
                                    {item.tab=='ask'?'问答':'分享'}
                                </span>
                                <span>{item.title}</span>
                                <span>
                                    {
                                        handleTime(item.last_reply_at)
                                    }
                                </span>
                            </li>
                        )
                    })
                }
            </div>
        )
    }
}
export default Topics;